import axios from 'axios';
import env from '../../build/env';
import Cookies from 'js-cookie';
import {Message} from 'iView';
const ajaxUrl = env === 'development'
    ? 'http://api.tl100.com/tool/api'//本机调试
    : env === 'production'
        ? 'http://api.tl100.com/tool/api'//生产环境
        : 'http://api.tl100.com/tool/api';//远程debug

const api = axios.create({
    baseURL: ajaxUrl,
    withCredentials: true,
    timeout: 5000
});

api.interceptors.request.use(function(config) {
    //设置请求默认token
    /* if (config.data) {
        config.data.token = '' || vm.$localStorage.get('token');
    }
    else
    {
        config.data = {token:vm.$localStorage.get('token')}
    } */
    return config;
}, function(error) {
    return Promise.reject(error);
});

//返回请求拦截，处理格式和token
api.interceptors.response.use(function (response) {

    if (response.status == 200) {
        if (response.data.res_code < -900) {
            //跳转登录
            Cookies.remove('islogin');
            Cookies.remove('userInfo');
            localStorage.clear();
            window.location.href = "/#/login";
        }
    } 
    if(response.status == 404){
        //跳转404
    }
    return response.data;
}, function (error) {
    if(/timeout/.test(error.toString())){
        Message.warning('请求超时,重新刷新页面~')
    }
    return Promise.reject(error);
});

export default api;
